/*
 * Copyright (c) 2011 Jean-Marc Perronne
 * Ensisa, 12 rue des Freres Lumieres, F-68093 Mulhouse cedex
 * All rights reserved.
 *
 * The copyright of this software is owned by Werner Randelshofer. 
 * You may not use, copy or modify this software, except in  
 * accordance with the license agreement you entered into with  
 * Jean-Marc Perronne. For details see accompanying license terms. 
 */

package fr.uha.ensisa.jmp.drone.handler;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;

import fr.uha.ensisa.jmp.drone.app.DroneConstants;
import fr.uha.ensisa.jmp.drone.com.BadInterfaceException;
import fr.uha.ensisa.jmp.drone.com.VideoConnection;
import fr.uha.ensisa.jmp.drone.video.codec.other.vi.BufferedVideoImage;


public class VideoHandler extends ChildDroneHandler<BufferedImage>
{
	private VideoConnection com;
	private BufferedVideoImage decoder;
	
	public VideoHandler(DroneHandler drone) throws SocketException, UnknownHostException, BadInterfaceException
	{
		super(drone);
		this.com = new VideoConnection();
		this.decoder = new BufferedVideoImage();

	}

	protected void videoWakeUp() throws IOException
	{
		//this.com.send("Hi".getBytes());
	    this.com.send(DroneConstants.WAKEUP_BYTES);
	}

	@Override
	public void run()
	{
		try
		{
			this.videoWakeUp();
			this.running();
			while(this.isActive() && this.drone.isActive())
			{
				try
				{
					ByteBuffer buffer = this.com.receive();
	              
					//long t=System.currentTimeMillis();
					
                    this.decoder.addImageStream(buffer);

                    BufferedImage picture = new BufferedImage(this.decoder.getWidth(), this.decoder.getHeight(), BufferedImage.TYPE_INT_RGB);
                    picture.setRGB(0, 0,this.decoder.getWidth(), this.decoder.getHeight(), this.decoder.getJavaPixelData(), 0, this.decoder.getWidth());
                    this.data().add(picture);
                    
                    //System.out.println("video : "+ String.valueOf(System.currentTimeMillis()-t));

					Thread.yield();
				}
				catch (SocketTimeoutException e)
				{
					//no data received, have to solicit drone
					e.printStackTrace();
					this.videoWakeUp();
				}
				catch (RuntimeException e)
				{
					e.printStackTrace();
				}
			}
		}
		catch (IOException e)
		{
			System.err.println("first video wakeup failed");
			e.printStackTrace();
		}
		finally
		{
			this.terminate();
			this.notRrunning();
		}
	}

	public void start()
	{
		super.start();
		new Thread(this).start();
	}
	
	@Override
	public void close()
	{
		this.com.close();
	}

}
